<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '200px'" class="el-aside">
      <el-scrollbar>
        <el-menu :default-active="activeMenu" class="el-menu-vertical" background-color="#141414" text-color="#fff"
          active-text-color="#409eff" :collapse="isCollapse" :collapse-transition="false" :unique-opened="true"
          @select="handleMenuSelect">
          <el-menu-item style="background: none !important;">
            <div class="flex">
              <img src="@/assets/imgs/logo.png" style="width: 30px;height: 30px;" />
              <span v-if="!isCollapse" style="padding-left: 10px;font-weight: bold;">{{ adminName }}</span>
            </div>
          </el-menu-item>
          <dynamic-menu :menu-list="menuList" />
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <el-container>
      <el-header class="layout-header">
        <div class="header-content">
          <div class="toggle-button" @click="toggleMenu">
            <el-icon v-if="isCollapse" size="18">
              <Expand />
            </el-icon>
            <el-icon v-else size="18">
              <Fold />
            </el-icon>
          </div>
          <div class="header-actions">
            <!-- <LanguageSwitch /> -->
            <ThemeToggle />
            <UserInfo />
          </div>
        </div>
      </el-header>

      <!-- 标签页 -->
      <TabBar />

      <el-main ref="mainContainer" class="layout-main" @scroll="handleScroll">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>

      <el-footer class="layout-footer">
        <p>©2025 {{ adminName }}
          <ServerTime />
        </p>
      </el-footer>
    </el-container>

    <div class="back-to-top" v-show="showBackToTop" @click="scrollToTop">
      <el-icon size="20">
        <CaretTop />
      </el-icon>
    </div>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { CaretTop } from '@element-plus/icons-vue'
import ThemeToggle from '../components/ThemeToggle.vue'
// import LanguageSwitch from '../components/LanguageSwitch.vue'
import ServerTime from '../components/ServerTime.vue'
import UserInfo from '../components/UserInfo.vue'
import TabBar from '../components/TabBar.vue'
import DynamicMenu from '../components/DynamicMenu.vue'
import { apiGetMenuTree } from '@/api/system/menu'
import { useUser } from '@/store/user'

const userStore = useUser()

const adminName = computed(() => userStore.params.AdminName || 'Admin')

interface MenuItem {
  id: number
  path: string
  name: string
  icon?: string
  children?: MenuItem[]
}

const route = useRoute()
const router = useRouter()
const isCollapse = ref(false)
const showBackToTop = ref(false)
const mainContainer = ref<InstanceType<typeof import('element-plus').ElMain>>()
const menuList = ref<MenuItem[]>([]) // 动态菜单数据

// 获取用户菜单数据
const fetchUserMenus = async () => {
  const res = await apiGetMenuTree()
  if (res.code === 200) {
    menuList.value = res.data
    // 检查当前路由是否存在于菜单中
    if (!isRouteExist(decodeURIComponent(route.fullPath), menuList.value)) {
      router.push(getFirstPath(menuList.value))
    }
  } else {
    ElMessage.error(res.message || '获取菜单失败')
  }
}

// 获取当前路由的第一个路径
const getFirstPath = (menuItems: MenuItem[]) => {
  let firstPath = "/";
  if (menuItems.length > 0) {
    if (menuItems[0].children && menuItems[0].children.length > 0) {
      firstPath = getFirstPath(menuItems[0].children)
    } else {
      firstPath = menuItems[0].path
    }
    localStorage.setItem('firstPath', firstPath)
  }
  return firstPath
}

// 判断当前路由是否存在于菜单中
const isRouteExist = (path: string, menuItems: MenuItem[]) => {
  for (const item of menuItems) {
    if (item.path === path) {
      return true
    }
    if (item.children && item.children.length > 0) {
      if (isRouteExist(path, item.children)) {
        return true
      }
    }
  }
  return false
}

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  const { fullPath } = route
  return decodeURIComponent(fullPath)
})

// 切换菜单折叠状态
const toggleMenu = () => {
  isCollapse.value = !isCollapse.value
}

// 处理菜单选择
const handleMenuSelect = (index: any) => {
  if (index.indexOf("http://") == 0 || index.indexOf("https://") == 0) {
    window.open(index, '_blank')
    return
  }
  router.push(decodeURIComponent(index))
}

const handleScroll = () => {
  if (mainContainer.value && mainContainer.value.$el) {
    const scrollTop = mainContainer.value.$el.scrollTop
    showBackToTop.value = scrollTop > 300
  }
}

const scrollToTop = () => {
  if (mainContainer.value && mainContainer.value.$el) {
    mainContainer.value.$el.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
  }
}

onMounted(() => {
  if (mainContainer.value && mainContainer.value.$el) {
    mainContainer.value.$el.addEventListener('scroll', handleScroll)
  }
  // 获取用户菜单数据
  fetchUserMenus()
})

onBeforeUnmount(() => {
  if (mainContainer.value && mainContainer.value.$el) {
    mainContainer.value.$el.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.el-aside {
  background-color: #141414;
  border-right: 1px solid var(--el-border-color);
  position: relative;
}

.el-menu-vertical {
  height: 100%;
  border: none;
}

.toggle-button {
  width: 32px;
  height: 32px;
  padding: 8px;
  background-color: var(--el-bg-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1;
}

.toggle-button:hover {
  background-color: var(--el-color-primary-light-9);
}

.layout-header {
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  padding: 0 20px 0 5px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.layout-main {
  background-color: var(--el-bg-color-page);
  padding: 10px;
}

.layout-footer {
  background-color: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  height: 40px;
}

.layout-footer p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.back-to-top {
  position: fixed;
  bottom: 80px;
  right: 30px;
  width: 40px;
  height: 40px;
  background-color: var(--el-color-primary);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transition: opacity 0.3s;
}

.back-to-top:hover {
  background-color: var(--el-color-primary-light-3);
}
</style>